package com.maweirdos.springSecurity.filter;

import com.maweirdos.springSecurity.domain.LoginUser;
import com.maweirdos.springSecurity.utils.JwtUtil;
import com.maweirdos.springSecurity.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * Author:  Maweirdos
 * Date:  2024/6/22 下午7:47
 * Description:  jwt认证过滤
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            // 过滤器链传递
            filterChain.doFilter(request, response);
            // 避免走下面的方法
            return;
        }
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            // 解析jwt，取出userId
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 从redis中取出用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        // 判断获取到的用户信息是否为空，因为redis里面可能并不存在这个用户信息，例如缓存过期了
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        //把最终的loginUser用户信息，通过setAuthentication方法，存入SecurityContextHolder,获取权限
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }
}
